package com.zhh.controller;

import com.zhh.common.ServerResponse;
import com.zhh.exception.UnauthorizedException;
import org.apache.shiro.ShiroException;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ExceptionController {

    final static Logger log = LoggerFactory.getLogger(ExceptionController.class);


    // 捕捉shiro的异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    @ResponseBody
    public ServerResponse handle401(ShiroException e) {
        return ServerResponse.createByErrorCodeMessage(401, e.getMessage());
    }

    // 捕捉UnauthorizedException
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    public ServerResponse handle401() {
        return ServerResponse.createByErrorCodeMessage(401, "Unauthorized");
    }

    // 捕捉其他所有异常
//    @ExceptionHandler(Exception.class)
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
//    @ResponseBody
//    public ServerResponse globalException(HttpServletRequest request, Throwable ex) {
//        log.error(ex.toString());
//        return ServerResponse.createByErrorCodeMessage(getStatus(request).value(), ex.getMessage());
//    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}

